import utils from '../../../utils/utils.js'
import Data from '../../../utils/data.js'
import User from "../../../utils/user.js";
import { HomeHttp } from '../../../api/home.js'
import { COUPON_COLUMN } from '../../../config/const.js'
import { servicePointMap, couponGoodsMap } from '../../../utils/dataMap.js'
import { getDistance, formatPassTime, formatTimeDate } from '../../../utils/vutils.js'
import { TABS_LIST } from './config.js'

const homeModel = new HomeHttp()

const app = getApp()
let statusBarHeight = wx.getSystemInfoSync()['statusBarHeight'] || 20 // 状态栏高度
let pageScrollPosTop = 0 //记录页面滚动位置

// 服务站（服务中心）、服务点、店铺关系
// 1. 服务站（服务中心）下有多个服务点和多个店铺
// 2. 服务点用于衔接服务站（服务中心）与门店，展示给用户，和自提点是等同的
// 3. 附近门店的获取需要通过从服务点中拿到服务站（服务中心）id，然后再获取附近店铺
Page({
  isTabBar: true,
  data: {
    searchValue:'',
    groupId: '',
    ekey: '',
    tabList: TABS_LIST,
    tabActive: 'nearby', // 主页 tab：推荐，附近 默认：推荐（recommend）

    defaultServiceCenterId: '', // 默认服务中
    serviceCenterId: wx.getStorageSync('store_service_id') || '', // 服务中心id
    servicePointInfo: wx.getStorageSync('servicePointInfo_2') || {}, // 服务点信息
    servicePointList: [], // 服务点列表
    isShowServiceCenterPopup: false, // 是否显示服务点选择弹框
    latitude: 0, // 维度 - 获取用户定位维度，用于获取服务点以及判断距离
    longitude: 0, // 经度 - 获取用户定位经度，用于获取服务点以及判断距离

    couponColumn: COUPON_COLUMN, // 优惠券栏目
    isShowDeliveryInfo: false, //是否显示底部订单配送
    isCouponInfo: false, //是否显示顶部优惠券
    isLoading: false, // 是否正在加载数据
    couponInfo: {}, // 优惠券信息
    deliveryOrderInfo: {}, // 配送订单信息

    notifyList: [], // 优惠券领取通知列表
    taskBanner: {}, // 任务banner图
    freeOrderBanner: {}, // 帮免单，赢现金banner图
    surplusTime: 0, // 优惠券显示倒计时
    seckillGoodsList: [], // 秒杀商品列表

    isHeaderTabsFixed: false, // 头部tab是否吸顶
    headerTabsTop: 0, // 头部tab top高度
    headerTabsHeight: 0, // 头部tab height高度
    pddClassifyTabsTop: 0, // 拼多多类目tab top高度
    statusBarHeight: statusBarHeight, // 状态栏高度
    initUser: true,
    openLogin: false,

    // seckillSelectStartTimeStr: '', // 当前选择秒杀时间（格式：字符串）
    // seckillTimeCurrentIndex: -1,
    // seckillTimeActiveIndex: -1, // 当前秒杀时间index
    // seckillTimeList: [], // 秒杀时间列表
  },

  async initPage(options) {
    let self = this
    // 订阅 changeServicePoint（修改服务站）
    app.event.on('changeServicePoint', this.onChangeServicePoint, this)
    this.setData({
      servicePointInfo: wx.getStorageSync('servicePointInfo_2') || {}
    })
    if (options.type && this.data.tabList[options.type]) {
      this.setData({
        tabActive: options.type
      })
    }
    Data.getDictConfig('pageConfig', function(res){
      self.setData({
        taskBanner: res.taskBanner,
        freeOrderBanner: res.freeBanner,
        defaultServiceCenterId: res.default_service_id
      });
    });
    this.setNavigationBar() // 设置导航bar样式
    this.switchUserHome() // 获取当前页面信息：获取 groupId，ekey
    this.showCoupon() // 通过判断是否显示优惠券
    this.httpGetCouponGainNotify() // 获取优惠券领取通知
    this.httpGetServiceByLocation() // 通过定位获取推荐服务
    this.initShare()
  },

  initShare() {
    this.shareOption['title'] = `社群团长返利平台`
    this.shareOption['path'] = `/pages/home/index/index?type=seckill`
    this.shareOption['imageUrl'] = `${this.data.static_host}/images/share/home.png?tm=1`
  },

  setNavigationBar () {
    wx.setBackgroundColor({
      backgroundColor: '#43B5E9', // 窗口的背景色为白色
    });
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#43B5E9',
    });
  },

  // 通过定位获取推荐服务
  async httpGetServiceByLocation(cb) {
    let self = this
    const { servicePointInfo } = this.data
    async function process () {
      await self.httpWxGetLocation()
        .catch(err => Promise.reject('NO_LOCATION'))
      if (servicePointInfo.pointId) {
        const { latitude, longitude } = self.data
        // 计算用户经纬度和缓存服务点经纬度的距离【是否超过】服务点的最大配送距离
        // >>> 如果超过最大配送距离，则请求附近的服务点
        let diffDistance = getDistance(latitude, longitude, servicePointInfo.latitude, servicePointInfo.longitude)
        if (diffDistance > servicePointInfo.maxDeliveryDistence) {
          await Promise.reject('OUT_RANGE')
        } else {
          wx.setStorageSync('servicePointInfo_2', servicePointInfo)
          await Promise.reject('EXIST_ONE_POINT')
        }
      } else {
        await Promise.reject('NO_POINT')
      }
    }
    try {
      cb(null, await process())
    } catch (err) {
      console.log('err', err)
      switch (err) {
        case 'NO_LOCATION': // 无法获取位置
        case 'NO_POINT': // 无服务点
        case 'OUT_RANGE': // 超出配送范围
          console.log('无法获取位置/无服务点/超出配送范围')
          await this.httpGetNearbyServicePoint()
          if (!this.data.isShowServiceCenterPopup) {
            await this.httpGetNearbyStore()
            // await this.httpGetGoodsRecommend()
            // await this.httpGetSeckillTimeGoods() // 获取秒杀商品
            // await this.httpGetSeckillTimePart() // 获取秒杀时间段
            // this.data.seckillTimeList.length && await this.httpGetSeckillTimeGoods() // 获取秒杀商品
          }
          break;
        case 'EXIST_ONE_POINT':
          console.log('存在一个服务点，设置为默认服务点')
          await this.httpGetNearbyStore()
          // await this.httpGetGoodsRecommend()
          // await this.httpGetSeckillTimeGoods() // 获取秒杀商品
          // await this.httpGetSeckillTimePart() // 获取秒杀时间段
          // this.data.seckillTimeList.length && await this.httpGetSeckillTimeGoods() // 获取秒杀商品
          break;
        default:
          break;
      }
    }
  },

  // 修改服务点
  async onChangeServicePoint (pointInfo) {
    const { servicePointInfo } = this.data
    console.log('servicePointInfo_2', servicePointInfo)
    if (pointInfo.pointId !== servicePointInfo.pointId) {
      this.setData({
        servicePointInfo: pointInfo,
        serviceCenterId: pointInfo.serviceCenterId,
        isShowServiceCenterPopup: false
      })
      wx.setStorageSync('servicePointInfo_2', pointInfo)
      await this.httpGetGoodsRecommend(false)
      await this.httpGetNearbyStore()
      // await this.httpGetSeckillTimeGoods() // 获取秒杀商品
      // await this.httpGetSeckillTimePart() // 获取秒杀时间段
      // this.data.seckillTimeList.length && await this.httpGetSeckillTimeGoods() // 获取秒杀商品
    }
  },

  showCoupon () {
    let coupon = app.globalData.couponInfo;
    if (coupon) {
      let time = new Date(coupon.end_time.replace(/-/g, "/")).getTime();
      var sTime = (time - new Date().getTime());
      if (sTime == -1) {
        return;
      }
      if (coupon.CouponStatus == 1 || coupon.coupon_status == 1) {
        this.setData({
          surplusTime: sTime,
          isCouponInfo: true,
          couponInfo: coupon
        })
      }
    }else{
      this.setData({
        isCouponInfo: false,
      });
    }
  },

  // 跳转到服务中心
  onNavToServiceCenter() {
    wx.navigateTo({
      url: `/pages/home/streetSearch/streetSearch`
    })
  },

  // 跳转至搜索页面
  onSearch() {
    this.data.tabList['nearby'].page = 1;
    this.httpGetNearbyStore(true);
  },

  onNavToTaskCenter() {
    if (!(this.data.userInfo && this.data.userInfo.uid)) {
      utils.msg('需要登录后才能操作哦!')
      return
    }
    utils.toPage({
      currentTarget:{
        dataset:{
          page:'/pages/task/index',
          type:'tabar',
        }
      }
    })
  },

  // tabs（商城，领券，本地） 切换
  onTabsItem(event) {
    const { tabList, tabActive } = this.data
    const { type } = event.currentTarget.dataset;
    if (type === tabActive) return
    tabList[tabActive].scrollTo = pageScrollPosTop
    this.setData({
      tabList: tabList,
      tabActive: type
    })
    let isThirdPlatform = ['pdd', 'jd'].includes(type)
    if (isThirdPlatform) {
      tabList[type].prefectureList && !tabList[type].prefectureList.length && this.httpGetPlatformClassify()
      tabList[type].classifyList && !tabList[type].classifyList.length && this.httpGetPlatformCouponPrefecture().then(() => {
        if (tabList[type].classifyTop === 0) {
          this.getClassifyTop()
        }
      })
      tabList[type].list && !tabList[type].list.length && this.httpSearchGoodsByPlatform()
    }
    wx.pageScrollTo({
      scrollTop: tabList[type].scrollTo,
      duration: 0
    })
  },

  // 领券栏目跳转
  onCouponColumn(event) {
    const columnId = event.detail.item.id;
    wx.navigateTo({
      url: `/pages/index/columnSearch/index?type=${columnId}`
    })
  },

  // 关闭服务点选择列表弹出层，获取第一个服务点作为默认服务点
  onCloseServicePointPopup() {
    this.onChangeServicePoint(this.data.servicePointList[0])
  },

  // 选择服务点
  onSelectServicePoint(event) {
    const { info } = event.detail // 服务站点信息
    this.onChangeServicePoint(info)
  },

  // 重新点位
  onReposition() {
    this.httpGetServiceByLocation()
  },

  // 第三方平台领券商品排序
  onGoodsSort (event) {
    let { classify, sort } = event.detail
    let { tabList, tabActive, statusBarHeight, headerTabsHeight } = this.data
    tabList[tabActive].page = 1
    tabList[tabActive].classifyId = classify
    tabList[tabActive].sort = sort
    this.setData({
      tabList: tabList
    })
    if (tabList[tabActive].isClassifySatisfy) {
      wx.pageScrollTo({
        scrollTop: tabList[tabActive].classifyTop - headerTabsHeight - statusBarHeight,
        duration: 0
      })
    }
    this.httpSearchGoodsByPlatform()
  },

  // 获取第三方平台类目高度
  getClassifyTop () {
    // 获取 .header-content 距离顶部位置，用于吸顶
    let self = this
    const { tabList, tabActive } = this.data
    wx.createSelectorQuery()
      .select('#' + tabList[tabActive].classifyTabId)
      .boundingClientRect(function(res) {
        if (res.top || res.height) {
          tabList[tabActive].classifyTop = res.top
          tabList[tabActive].classifyHeight = res.height
          console.log('获取第三方平台类目top height：', res.top, res.height)
          self.setData({
            tabList: tabList
          })
        }
      }).exec();
  },

  //获取底部配送信息
  httpGetBottonDeliverOrder() {
    return homeModel.getBottonDeliverOrder({},false).then((res) => {
      if (res && res.unionOrderId) {
        this.setData({
          isShowDeliveryInfo: true,
          deliveryOrderInfo: res
        })
      } else {
        this.setData({
          isShowDeliveryInfo: false
        })
      }
    })
  },

  // 获取附近服务点
  httpGetNearbyServicePoint() {
    const { longitude, latitude } = this.data; // 经纬度信息
    return homeModel.getNearbyServicePoint({
      lng: longitude, // 经度
      lat: latitude, // 纬度
      page: 1,
      page_size: 4
    }).then((res) => {
      // 1. 判断服务点是否超过 1个
      // 2. 如果超过1个服务点，弹窗供用户选择，如果只有1个服务点，默认获取，不弹窗选择
      let isShowService = res.service_point.length > 1
      let servicePointListArr = servicePointMap(res.service_point) // 服务站列表
      !isShowService && wx.setStorageSync('servicePointInfo_2', servicePointListArr[0])
      this.setData({
        servicePointList: servicePointListArr, // 服务站信息
        servicePointInfo: isShowService ? {} : servicePointListArr[0],
        serviceCenterId: isShowService ? '' : servicePointListArr[0].serviceCenterId,
        isShowServiceCenterPopup: isShowService
      })
    })
  },

  // 获取推荐商品列表
  httpGetGoodsRecommend(isLoading) {
    return true;
    const {
      tabList,
      serviceCenterId
    } = this.data;
    let param = {
      page: tabList['recommend'].page,
      page_size: tabList['recommend'].pageSize,
      client_type: 3
    };
    if (serviceCenterId) {
      param['store_service_id'] = utils.fixInt(serviceCenterId);
    }
    return homeModel.getGoodsRecommend(param, isLoading).then((res) => {
      let page = tabList['recommend'].page
      let resMap = couponGoodsMap(res.recommend_list, 'recommend')
      if (page === 1) {
        tabList['recommend'].list = resMap
      } else {
        let list = tabList['recommend'].list
        tabList['recommend'].list = list.concat(resMap)
      }
      tabList['recommend'].totalNum = res.total
      this.setData({
        tabList: tabList
      })
    })
  },

  // 获取附近商家
  httpGetNearbyStore(isLoading) {
    const {
      servicePointInfo,
      latitude,
      longitude,
      searchValue,
      tabList
    } = this.data
    return homeModel.getNearbyStore({
      page: tabList['nearby'].page,
      page_size: tabList['nearby'].pageSize,
      store_service_id: servicePointInfo.serviceCenterId,
      store_name:searchValue,
      lng: longitude, // 经度
      lat: latitude // 纬度
    }, isLoading).then((res) => {
      let page = tabList['nearby'].page
      let resMap = res.store_list || []
      if (page === 1) {
        tabList['nearby'].list = resMap
      } else {
        let list = tabList['nearby'].list
        tabList['nearby'].list = list.concat(resMap)
      }
      tabList['nearby'].totalNum = res.total
      this.setData({
        tabList: tabList,
        serviceCenterId: servicePointInfo.serviceCenterId
      })
    })
  },

  // 获取地理位置信息
  httpWxGetLocation() {
    let self = this
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'wgs84',
        success: function(res) {
          self.setData({
            longitude: res.longitude, // 经度
            latitude: res.latitude // 维度
          })
          resolve(res)
        },
        fail: function(err) {
          reject(err)
        }
      })
    })
  },

  // 获取当前页面信息
  switchUserHome() {
    let userHome = User.getUserHome(this.options);
    this.channel = userHome.channel;
    this.setData({
      ekey: this.channel.ekey,
      groupId: this.channel.shareUid
    });
    return userHome;
  },

  // 获取服务点（店铺）信息
  httpGetStoreInfo(id) {
    const { longitude, latitude } = this.data
    return homeModel.getStoreInfo({
      store_id: id,
      lng: longitude, // 经度
      lat: latitude // 纬度
    }).then((res) => {
      this.setData({
        servicePointInfo: servicePointMap([res.store_info])
      })
    })
  },

  // 获取平台优惠券专区列表
  httpGetPlatformCouponPrefecture () {
    const { tabActive, tabList } = this.data
    return homeModel.getPlatformCouponPrefecture({
      platform_type: tabList[tabActive].platformType, // 平台类型 - 1：拼多多 2：淘宝 3：京东
    }).then((res) => {
      tabList[tabActive].prefectureList = res.recommend
      this.setData({
        tabList: tabList
      })
    })
  },

  // 获取平台类目列表
  httpGetPlatformClassify () {
    const { tabActive, tabList } = this.data
    return homeModel.getPlatformClassify({
      platform_type: tabList[tabActive].platformType, // 平台类型 - 1：拼多多 2：淘宝 3：京东
      level: 1 // 返回类目级别, 默认为 1
    }).then((res) => {
      let classifyList = res.goods_opts
      classifyList.unshift({
        opt_id: '',
        opt_name: '热门',
        goods_opts_list: null
      })
      tabList[tabActive].classifyList = classifyList
      this.setData({
        tabList: tabList
      })
    })
  },

  // 通过平台对商品进行搜索：拼多多、淘宝、京东
  httpSearchGoodsByPlatform () {
    const { tabActive, tabList } = this.data
    let requestData = {
      page: tabList[tabActive].page,
      page_size: tabList[tabActive].pageSize,
      sort_type: tabList[tabActive].sort, // 排序类型：0-综合排序;3-按价格升序;4-按价格降序;5-按销量升序;6-按销量降序;13-按佣金金额升序排序;14-按佣金金额降序排序
      platform_type: tabList[tabActive].platformType, // 平台类型 - 1：拼多多 2：淘宝 3：京东
      has_coupon: false // 是否有优惠券, 默认true
    }
    if (tabList[tabActive].classifyId) {
      requestData.opt_id = tabList[tabActive].classifyId
    }
    return homeModel.searchGoodsByPlatform(requestData).then((res) => {
      let page = tabList[tabActive].page
      let resMap = couponGoodsMap(res.goods_list)
      if (page === 1) {
        tabList[tabActive].list = resMap
      } else {
        let list = tabList[tabActive].list
        tabList[tabActive].list = list.concat(resMap)
      }
      tabList[tabActive].totalNum = res.total_count
      this.setData({
        tabList: tabList
      })
    })
  },

  // 获取优惠券领取通知
  httpGetCouponGainNotify() {
    return homeModel.getCouponGainNotify().then(res => {
      let resMap = []
      if (res.news) {
        resMap = res.news.map(item =>{
          return {
            nickName: item.nickName, // 昵称
            avatar: item.avatar, // 头像
            couponPrice: item.money, // 优惠前价钱
            dividePrice: item.commission, // 分成金额
            passTime: formatPassTime(item.ctime * 1000), // 领券时间
            platform: item.platform_type
          }
        })
      }
      this.setData({
        notifyList: resMap
      })
    })
  },

  // 获取秒杀时间段
  // httpGetSeckillTimePart() {
  //   const { servicePointInfo } = this.data
  //   return homeModel.getSeckillTimePart({
  //     store_service_id: servicePointInfo.serviceCenterId || wx.getStorageSync('servicePointInfo_2').serviceCenterId
  //   }).then(res => {
  //     let activeIndex = -1
  //     let resMap = res.seckill_time.map((item, index) => {
  //       // let nowTimestamp = new Date().getTime()
  //       let startTimestamp = this.formatStrTimeToTimestamp(item.start_time)
  //       let endTimestamp = this.formatStrTimeToTimestamp(item.end_time)
  //       let timeSeckillDesc = ''
  //       if (item.status === 3) {
  //         timeSeckillDesc = '即将开始'
  //         activeIndex = activeIndex === -1 ? index : activeIndex
  //       } else if (item.status === 2) {
  //         timeSeckillDesc = '已结束'
  //       } else if (item.status === 1) {
  //         timeSeckillDesc = '热抢中'
  //         activeIndex = activeIndex === -1 ? index : activeIndex
  //       }
  //       return {
  //         startTimeStr: item.start_time,
  //         endTimeStr: item.end_time,
  //         startTimestamp: startTimestamp,
  //         endTimestamp: endTimestamp,
  //         seckillStatus: item.status, // 当前时间段秒杀状态
  //         timeSeckillDesc: timeSeckillDesc
  //       }
  //     })
  //     // const { tabList } = this.data
  //     // let resMapLen = resMap.length - 1 > 0 ? resMap.length - 1 : 0
  //     activeIndex = activeIndex === -1 ? resMap.length - 1 : activeIndex
  //     // tabList['seckill'].isShow = activeIndex === -1 ? false : true
  //     this.setData({
  //       // tabList: tabList,
  //       seckillTimeActiveIndex: activeIndex,
  //       seckillTimeCurrentIndex: activeIndex,
  //       seckillTimeList: resMap,
  //       seckillSelectStartTimeStr: resMap[activeIndex] ? resMap[activeIndex].startTimeStr : ''
  //     })
  //   })
  // },

  // 格式化字符串时间为时间戳
  // formatStrTimeToTimestamp(str) {
  //   let currentYMD = formatTimeDate(new Date(), 'yyyy/MM/dd')
  //   let fullStrTime = `${currentYMD} ${str}`
  //   return new Date(fullStrTime).getTime()
  // },

  // 获取秒杀时间段的商品列表
  httpGetSeckillTimeGoods() {
    const { tabList, seckillSelectStartTimeStr, defaultServiceCenterId, servicePointInfo } = this.data
    return homeModel.getSeckillTimeGoods({
      // now_time: seckillSelectStartTimeStr || formatTimeDate(new Date(), 'hh:mm'),
      store_service_id: defaultServiceCenterId || servicePointInfo.serviceCenterId || wx.getStorageSync('servicePointInfo_2').serviceCenterId,
      page: tabList['seckill'].page,
      pageSize: tabList['seckill'].pagesize
    }, {
      isNeedResponseTime: true
    }).then(res => {
      let resMap = []
      let nowTimestamp = res.tm
      if (res.seckill_goods) {
        resMap = res.seckill_goods.map(item => {
          let startTimestamp = (item.start_time - nowTimestamp) * 1000
          let endTimestamp = (item.end_time - nowTimestamp) * 1000
          return {
            goodsId: item.goods_id, // 商品id
            goodsName: item.goods_title, // 商品名称
            goodSThumbnailImg: item.goods_thumbnail_url, // 商品id
            goodsUnit: item.sku_unit, // 商品单位
            joinNum: item.sales_volume, // 参与人数 与 提醒人数
            goodsPrice: item.goods_price, // 商品原价
            seckillPrice: item.member_goods_price, // 商品秒杀价
            isSetAlert: item.subscribe_status === 1 ? true : false, // 是否设置提醒： 1已设置提醒 2未设置提醒
            limitNum: item.stock_amount, // 限量（库存）/剩余
            seckillStatus: item.spike_status, // 秒杀状态：1:热抢中，2:已结束，3:未开抢
            startTimestamp: startTimestamp > 0 ? startTimestamp : 0, // 秒杀开始时间
            endTimestamp: endTimestamp > 0 ? endTimestamp : 0 // 秒杀结束时间
          }
        })
      }
      tabList['seckill'].list = tabList['seckill'].page === 1 ? resMap : tabList['seckill'].list.concat(resMap)
      tabList['seckill'].totalNum = res.total
      this.setData({
        tabList: tabList
      })
    })
  },

  // 页面相关事件处理函数--监听用户下拉动作：获取推荐商品数据 或者 获取附近店铺数据
  onPullDownRefresh: async function() {
    let { tabList, tabActive } = this.data
    tabList[tabActive].page = 1
    this.setData({
      tabList: tabList
    })
    try {
      switch (tabList[tabActive].type) {
        case 'recommend':
          await this.httpGetGoodsRecommend()
          await this.httpGetNearbyStore()
          // await this.httpGetSeckillTimePart()
          // await this.httpGetSeckillTimeGoods()
          break
        case 'nearby':
          await this.httpGetNearbyStore()
          break
        case 'seckill':
          // await this.httpGetSeckillTimeGoods()
          break
        case 'pdd':
        case 'jd':
          await this.httpSearchGoodsByPlatform()
          break
        default:
          break
      }
      wx.stopPullDownRefresh()
    } catch {
      wx.stopPullDownRefresh()
    }

  },

  // 页面上拉触底事件的处理函数：获取推荐商品数据 或者 获取附近店铺数据
  onReachBottom: async function() {
    let { tabList, tabActive, isLoading } = this.data
    if (isLoading) return
    let tab = tabList[tabActive]
    let currentListNum = tab.list.length
    let totalNum = tab.totalNum
    if (currentListNum < totalNum) {
      tabList[tabActive].page = tabList[tabActive].page + 1
      this.setData({
        tabList: tabList,
        isLoading: true
      })
      try {
        switch (tab.type) {
          case 'recommend':
            // await this.httpGetGoodsRecommend()
            break
          case 'nearby':
            await this.httpGetNearbyStore()
            break
          case 'seckill':
            // await this.httpGetSeckillTimeGoods()
            break
          case 'pdd':
          case 'jd':
            await this.httpSearchGoodsByPlatform()
            break
          default:
            break
        }
        this.setData({
          isLoading: false
        })
      } catch {
        this.setData({
          isLoading: false
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      userInfo: app.globalData.userInfo
    });
    let self = this;
    // 获取 .header-content 距离顶部位置，用于吸顶
    if (this.data.headerTabsTop === 0) {
        wx.createSelectorQuery()
          .select('.header-content')
          .boundingClientRect(function(res) {
            console.log('header-content res', res)
            if (res.top || res.height) {
              self.setData({
                headerTabsTop: res.top,
                headerTabsHeight: res.height
              })
            }
          }).exec();
      }
    if (this.data.userInfo && this.data.userInfo.uid) {
      this.httpGetBottonDeliverOrder() //底部配送信息
    }
    // if (!wx.getStorageSync('servicePointInfo_2')) {
    //   this.httpGetServiceByLocation()
    // }
    let coupon = app.globalData.couponInfo;
    if (coupon) {
      let time = new Date(coupon.end_time.replace(/-/g, "/")).getTime();
      let sTime = (time - new Date().getTime());
      if (sTime == -1) {
        return;
      }
      if (coupon.CouponStatus == 1 || coupon.coupon_status == 1) {
        this.setData({
          surplusTime: sTime,
          isCouponInfo: true,
          couponInfo: coupon
        })
      }
    }else{
      this.setData({
        isCouponInfo: false,
      });
    }
  },

  //页面影藏时
  onHide: function() {
    this.setData({
      isCouponInfo: false,
    });
  },

  // 监听页面滚动
  onPageScroll: function(event) {
    // 首页tab吸顶
    let scrollTop = parseInt(event.scrollTop)
    pageScrollPosTop = scrollTop
    let { tabList, tabActive, headerTabsTop, headerTabsHeight, statusBarHeight, isHeaderTabsFixed } = this.data
    let isHeaderSatisfy = (scrollTop + statusBarHeight) >= headerTabsTop ? true : false
    let isThirdPlatform = ['pdd', 'jd'].includes(tabActive)
    if (isThirdPlatform && tabList[tabActive].classifyTop !== 0) { // && tabList[tabActive].classifyTop !== 0
      let classifyTop = tabList[tabActive].classifyTop
      let isClassifySatisfy = (scrollTop + statusBarHeight + headerTabsHeight) >= classifyTop ? true : false
      if (tabList[tabActive].isClassifySatisfy !== isClassifySatisfy) {
        tabList[tabActive].isClassifySatisfy = isClassifySatisfy
        tabList[tabActive].classifySatisfyClass = isClassifySatisfy
          ? `position: fixed; top: ${headerTabsHeight + statusBarHeight}px; left: 0; right: 0; z-index: 999`
          : ''
        this.setData({
          tabList: tabList
        })
      }
    }
    if (isHeaderTabsFixed !== isHeaderSatisfy) {
      this.setData({
        isHeaderTabsFixed: isHeaderSatisfy
      })
    }

  },

  // 生命周期函数--监听页面卸载
  onUnload: function() {
    // 注销所订阅的 changeServicePoint 事件
    app.event.off('changeServicePoint', this.onChangeServicePoint)
  },

  // 剩余时间
  timeSurplus(dateTimeStamp) {
    var now = new Date().getTime();
    var diffValue = dateTimeStamp - now;
    return result;
  },
  onChange:function(e) {
    this.setData({
      searchValue: e.detail
    });
  },
  // onShareAppMessage() {
  //   let _param, pages, currentPage;
  //   let _share = {
  //     title: '巷友-社群团长返利',
  //     path: `pages/home/index/index?type=seckill`,
  //     image: `${this.data.static_host}/images/share/home.png`
  //   };
  //   let channel = User.getShareParam(0);
  //   if (!_share.title) {
  //     _share['title'] = '快来领取优惠券吧';
  //   }
  //   if (!_share.url) {
  //     pages = getCurrentPages();
  //     currentPage = pages[pages.length - 1];
  //     _share['url'] = currentPage.route;
  //   }
  //   if (_share['url'].indexOf('?') === -1) {
  //     _share['url'] += '?v=' + utils.version;
  //   }
  //   if (channel.hasOwnProperty('ekey') && channel.ekey && _share['url'].indexOf('ekey') === -1) {
  //     _share['url'] += '&ekey=' + channel['ekey'];
  //   }
  //   if (channel.hasOwnProperty('shareUid') && channel.shareUid > 0 && _share['url'].indexOf('uid') === -1) {
  //     _share['url'] += '&uid=' + channel['shareUid'];
  //   }
  //   console.log('share', _share['url'])
  //   _param = {
  //     title: _share['title'],
  //     path: _share['url']
  //   };
  //   if (_share['image']) {
  //     _param['imageUrl'] = _share['image'];
  //   }
  //   this.isShareLoading = true;
  //   utils.log('分享参数', _param, 'channel:', channel);
  //   return _param;
  // }
});
